<template>
    <div class="app-container">
        <el-card class="operate-container" shadow="never">
            <!-- <el-button size="mini" class="btn-add" @click="createAdd()" >添加活动</el-button> -->
            <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
                <el-form-item label="活动分类：">
                    <el-select v-model="listQuery.categoryId" placeholder="请选择类别">
                        <el-option
                            v-for="item in listLei"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="活动状态：">
                    <el-select v-model="listQuery.activityStatus" placeholder="请选择状态">
                        <el-option
                            v-for="item in lisState"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="搜索：">
                    <el-input v-model="listQuery.activityName" class="input-width" placeholder="请输入活动名称" clearable></el-input>
                </el-form-item>
            </el-form>
            <div style="display: flex;">
                <el-button
                    style="float:right"
                    type="primary"
                    @click="handleSearchList()"
                    size="small">
                    查询搜索
                </el-button>
                <el-button
                    style="float:right;margin-right: 15px"
                    @click="handleResetSearch()"
                    size="small">
                    重置
                </el-button>
                <el-button size="mini" class="btn-add" @click="createAdd()" >添加活动</el-button>
            </div>
        </el-card>
        <div class="table-container">
            <el-table ref="adminTable"
                    :data="list"
                    style="width: 100%;"
                    v-loading="listLoading" border>
                <el-table-column label="活动ID" width="100" align="center">
                    <template slot-scope="scope">{{scope.row.activityId}}</template>
                </el-table-column>
                <el-table-column label="活动分类" align="center">
                    <template slot-scope="scope">{{scope.row.categoryId === 1 ? '体育': scope.row.categoryId === 2 ? '演唱会': '音乐节'}}</template>
                </el-table-column>
                <el-table-column label="活动名称（简）" align="center">
                    <!-- <template slot-scope="scope">{{ scope.row.zhCnName }}</template> -->
                    <template slot-scope="scope"><div v-html="hightLight(listQuery.activityName, scope.row.zhCnName)"></div></template>
                </el-table-column>
                <el-table-column label="活动名称（繁）" align="center">
                    <template slot-scope="scope">{{scope.row.zhHkName }}</template>
                </el-table-column>
                <el-table-column label="活动地点" width="160" align="center">
                    <template slot-scope="scope">{{scope.row.address}}</template>
                </el-table-column>
                <el-table-column label="活动时间" width="300" align="center">
                    <template slot-scope="scope">{{scope.row.startTime | formatDateTime}} - {{scope.row.endTime | formatDateTime}}</template>
                </el-table-column>
                <el-table-column label="进驻票务" width="160" align="center">
                    <template slot-scope="scope">{{scope.row.ticketsUsers}}</template>
                </el-table-column>
                <el-table-column label="活动状态" width="140" align="center">
                    <template slot-scope="scope">
                    {{ showStatus(scope.row.status) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="240" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini"
                                    type="text"
                                    @click="handleSee(scope.$index, scope.row)">手机预览
                        </el-button>
                        <el-button size="mini"
                                    type="text"
                                    @click="handleUpdate(scope.$index, scope.row)">详情
                        </el-button>
                        <el-button size="mini"
                                    type="text"
                                    @click="handleRouter(scope.$index, scope.row)">须知
                        </el-button>
                        <el-button size="mini"
                                    type="text"
                                    @click="handleShow(scope.$index, scope.row)">
                                    {{scope.row.enabled ? '隐藏' : '显示'}}
                        </el-button>
                        <el-button size="mini"
                                    type="text"
                                    @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery.pageNum"
            :page-size="listQuery.pageSize"
            :page-sizes="[10,15,20]"
            :total="total">
            </el-pagination>
        </div>

        <el-dialog
            :title="'添加/编辑活动'"
            :visible.sync="visible"
            width="75%">
            <el-form :model="activityResource"
                    ref="thirdForm"
                    :rules="rules"
                    label-width="200px" size="small">
                <el-form-item label="活动分类：" prop="categoryId">
                    <el-radio-group v-model="activityResource.categoryId">
                        <el-radio :label="1">体育</el-radio>
                        <el-radio :label="2">演唱会</el-radio>
                        <el-radio :label="3">音乐节</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="活动名称（简）：" prop="zhCnName">
                    <el-input v-model="activityResource.zhCnName" class="input-width" placeholder="请输入活动名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="活动名称（繁）：" prop="zhHkName">
                    <el-input v-model="activityResource.zhHkName" class="input-width" placeholder="请输入活动名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="活动地点：" prop="address">
                    <el-select v-model="activityResource.address" clearable
                        filterable
                        remote
                        :remote-method="queryZu"
                         placeholder="请搜索"  >
                        <el-option
                        v-for="item in thirdOptions"
                        :key="item.id"
                        :label="item.cn ? item.country.cn + ' ' + item.cn : item.country.cn + ' ' + item.name"
                        :value="item.cn ? item.country.cn + ' ' + item.cn : item.country.cn + ' ' + item.name ">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="活动地址（简）：" prop="zhCnAddress">
                    <el-input v-model="activityResource.zhCnAddress" class="input-width" placeholder="请输入活动地址" clearable></el-input>
                </el-form-item>
                <el-form-item label="活动地址（繁）：" prop="zhHkAddress">
                    <el-input v-model="activityResource.zhHkAddress" class="input-width" placeholder="请输入活动地址" clearable></el-input>
                </el-form-item>
                <el-form-item label="活动时间：">
                    <div>
                        <el-date-picker
                            v-model="loginTime"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                        <el-button @click="addTime" size="small">添加</el-button>
                    </div>
                    <div v-for="(item, index) in activityShows" style="margin: 10px;">
                        <span>活动时间{{ index + 1 }}：</span>
                        <span v-if="item.flag" style="display: inline-block;width: 190px;">{{ item.startTime }} </span>
                        <span v-if="item.flag" style="display: inline-block;width: 190px;">{{ item.endTime }}</span>
                        <span v-if="item.flag" style="display: inline-block;width: 90px;">{{ item.status === 0 ? '正常' : item.status === 1 ? '取消' : '延期'}}</span>
                        <el-date-picker
                            v-if="!item.flag"
                            v-model="loginNewTime"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                        <el-select  v-if="!item.flag" v-model="item.status" placeholder="请选择状态" style="width: 110px;">
                            <el-option
                                v-for="item in typeList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                        <el-button v-if="item.flag" @click="upTime(index)" class="liang" size="small">修改</el-button>
                        <el-button v-if="!item.flag" @click="sureTime(index)" class="liang" size="small">确认</el-button>
                        <el-button @click="deleteTime(index)" size="small">删除</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="活动标签（简）：">
                    <div>
                        <el-input v-model="zhCnLabel" class="input-width" maxlength="5" placeholder="请输入活动标签" clearable></el-input>
                        <el-button @click="cnAdd" size="small">添加</el-button>
                    </div>
                    <div class="select-arr">
                        <div class="div1" v-for="(item, index) in activityResource.zhCnLabels">
                            <div class="div2">
                                {{item}}
                            </div>
                            <div class="div3">
                                <i class="el-icon-close" @click="delData(index, 'cn')"></i>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="活动标签（繁）：">
                    <div>
                        <el-input v-model="hkLabel" class="input-width" maxlength="5" placeholder="请输入活动标签" clearable></el-input>
                        <el-button @click="hkAdd" size="small">添加</el-button>
                    </div>
                    <div class="select-arr">
                        <div class="div1" v-for="(item, index) in activityResource.zhHkLabels">
                            <div class="div2">
                                {{item}}
                            </div>
                            <div class="div3">
                                <i class="el-icon-close" @click="delData(index, 'hk')"></i>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="活动宣传图：">
                    <el-upload
                            ref="uploadFileList"
                            action=""
                            class="upload-demo"
                            style="display:inline-block;max-width: 670px;"
                            :limit="1"
                            multiple
                            list-type="text"
                            accept=".png"
                            :before-upload="beforeUpload">
                        <img v-if="activityResource.img[0]" :src="activityResource.img[0]" style="width: 100px;height: 100px;" class="avatar">
                        <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                        <el-button size="small">上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="座位图：">
                    <el-upload
                            ref="uploadFileList"
                            action=""
                            class="upload-demo"
                            style="display:inline-block;max-width: 670px;"
                            :limit="1"
                            multiple
                            list-type="text"
                            accept=".png"
                            :before-upload="beforeUploadS">
                        <img v-if="activityResource.seatsImg[0]" :src="activityResource.seatsImg[0]" style="width: 100px;height: 100px;" class="avatar">
                        <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                        <el-button size="small">上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="活动详情：" prop="zhHkDescription">
                    <div>
                        <div>
                            <el-button :class="{liang: nameType === 'c'}" @click="changeType('c')" size="small">简</el-button>
                            <el-button :class="{liang: nameType === 'h'}" @click="changeType('h')" size="small">繁</el-button>
                        </div>
                        <div>
                            <div v-if="nameType === 'c'">
                                <Editor :height="300" v-model="activityResource.zhCnDescription"></Editor>
                            </div>
                            <div v-if="nameType === 'h'">
                                <EditorHK :height="300" v-model="activityResource.zhHkDescription"></EditorHK>
                            </div>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="visible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="dialogConfirm('thirdForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :title="'手机预览'"
            :visible.sync="visibleHtml"
            width="45%">
            <div style="display: flex;justify-content: center;">
                <iframe :src="htmlV" width="300" height="400"></iframe>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="visibleHtml = false" size="small">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment'
import { activityList, activityDelete, activityShow, cityList, uploadImg, activityAdd, activityUpdate, fetchAllResourceList }  from '@/api/app';
import {formatDate} from '@/utils/date';
import Editor from '@/components/Editor';
import EditorHK from '@/components/EditorHK';
const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    activityName: null,
    categoryId: null,
    activityStatus: null,
};
const defaultResource = {
    activityId: null,
    categoryId: null,
    zhCnName: null,
    zhHkName: null,
    address: null,
    zhCnAddress: null,
    zhHkAddress: null,
    activityShows: [],
    zhCnLabels: [],
    zhHkLabels: [],
    img: [],
    seatsImg: [],
    ticketsUtId: [],
    zhCnDescription: null,
    zhHkDescription: null,
}
export default{
    components: {
        Editor,
        EditorHK,
    },
    data() {
        return {
            listQuery: Object.assign({}, defaultListQuery),
            list: [],
            listLoading: false,
            total: 0,
            listLei: [
                {
                    id: 1,
                    name: '体育'
                },
                {
                    id: 2,
                    name: '演唱会'
                },
                {
                    id: 3,
                    name: '音乐节'
                },
            ],
            lisState: [
                {
                    id: 0,
                    name: '未开始'
                },
                {
                    id: 1,
                    name: '进行中'
                },
                {
                    id: 2,
                    name: '已结束'
                },
            ],
            typeList: [
                {
                    id: 0,
                    name: '正常'
                },
                {
                    id: 1,
                    name: '取消'
                },
                {
                    id: 2,
                    name: '延期'
                },
            ],
            rules: {
                categoryId: [
                    { required: true, message: '请选择活动分类' }
                ],
                zhCnName: [
                    { required: true, message: '请填写活动名称' }
                ],
                zhHkName: [
                    { required: true, message: '请填写活动名称' }
                ],
                address: [
                    { required: true, message: '请选择活动地点' }
                ],
                zhCnAddress: [
                    { required: true, message: '请填写活动地址' }
                ],
                zhHkAddress: [
                    { required: true, message: '请填写活动地址' }
                ],
                activityShows: [
                    { required: true, message: '请添加活动时间' }
                ],
                zhCnLabels: [
                    { required: true, message: '请添加活动标签' }
                ],
                zhHkLabels: [
                    { required: true, message: '请添加活动标签' }
                ],
                img: [
                    { required: true, message: '请选择宣传图' }
                ],
                seatsImg: [
                    { required: true, message: '请选折座位图' }
                ],
                zhCnDescription: [
                    { required: true, message: '请填写活动详情' }
                ],
                zhHkDescription: [
                    { required: true, message: '请填写活动详情' }
                ],
            },
            visible: false,
            activityResource: Object.assign({}, defaultResource),
            thirdOptions: [],
            loginTime: null,
            loginNewTime: null,
            zhCnLabel: null,
            hkLabel: null,
            nameType: 'c',
            activityShows: [],
            visibleHtml: false,
            htmlV: null,
            btnMenu: {
                edit: true,
                delete: true,
            }
        }
    },
    created() {
        const menu = JSON.parse(localStorage.getItem('listMenu'));
        const item = menu.filter(item => item.title === '活动列表')[0];
        fetchAllResourceList({menuId: item.id }).then(res => {
            res.data.forEach(dom => {
            if (dom.component === '' && dom.name === '后台角色管理') {
                this.btnMenu.edit = false;
            }
            if (dom.component === '' && dom.name === '后台角色删除') {
                this.btnMenu.delete = false;
            }
            });
        });
        this.getList();
    },
    filters: {
        formatDateTime(time) {
          if (time == null || time === '') {
            return '-';
          }
          let date = new Date(time);
          return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
        }
    },
    methods: {
        hightLight (keyWord, suggtion) {
            // 使用 regexp 构造函数，因为这里要匹配的是一个变量
            let newSrt = null;
            const reg = new RegExp(keyWord, 'ig')
            if (keyWord && suggtion) {
                newSrt = String(suggtion).replace(reg, function (p) {
                    return '<span style="color: #409EFF">' + p + '</span>'
                })
            } else {
                newSrt = suggtion;
            }
            return newSrt
        },
        changeType(type) {
            this.nameType = type;
        },
        beforeUpload(file) {
            if (file.size === 0) {
                this.$notify({
                    title: '失败',
                    message: '不存在上传文件',
                    type: 'error',
                    duration: 2000
                })
                return false
            }
            // const isJPG = file.type === 'image/jpeg';
            // const isLt2M = file.size / 1024 / 1024 < 2;

            // if (!isJPG) {
            // this.$message.error('上传头像图片只能是 JPG 格式!');
            // }
            // if (!isLt2M) {
            // this.$message.error('上传头像图片大小不能超过 2MB!');
            // }
            // return isJPG && isLt2M;
            const fileData = new FormData();
            fileData.append('avatar', file);
            const from = new FormData();
            from.append('file', file);
            from.append('type', 1);
            uploadImg(from).then(res => {
                this.activityResource.img = [];
                this.activityResource.img.push(res.data);
            });
        },
        beforeUploadS(file) {
            if (file.size === 0) {
                this.$notify({
                    title: '失败',
                    message: '不存在上传文件',
                    type: 'error',
                    duration: 2000
                })
                return false
            }
            const fileData = new FormData();
            fileData.append('avatar', file);
            const from = new FormData();
            from.append('file', file);
            from.append('type', 1);
            uploadImg(from).then(res => {
                this.activityResource.seatsImg = [];
                this.activityResource.seatsImg.push(res.data);
            });
        },
        cnAdd() {
            if (this.zhCnLabel) {
                if (this.activityResource.zhCnLabels.length === 3) {
                    this.$message({
                        type: 'error',
                        message: '最多可添加三个标签!'
                    });
                } else {
                    this.activityResource.zhCnLabels.push(this.zhCnLabel);
                }
            }
        },
        hkAdd() {
            // console.log(this.hkLabel, this.activityResource.zhHkLabels);
            if (this.hkLabel) {
                if (this.activityResource.zhHkLabels.length === 3) {
                    this.$message({
                        type: 'error',
                        message: '最多可添加三个标签!'
                    });
                } else {
                    this.activityResource.zhHkLabels.push(this.hkLabel);
                }
            }
        },
        delData(index, type) {
            if (type === 'cn') {
                this.activityResource.zhCnLabels.splice(index, 1);
            } else {
                this.activityResource.zhHkLabels.splice(index, 1);
            }
        },
        getList() {
            this.listLoading = true;
            activityList(this.listQuery).then(res => {
                this.listLoading = false;
                this.list = res.data.records;
                this.total = res.data.total;
            });
        },
        createAdd() {
            this.loginTime = null;
            this.loginNewTime = null;
            this.zhCnLabel = null;
            this.hkLabel = null;
            this.activityResource = Object.assign({}, defaultResource);
            this.visible = true;
        },
        queryZu(key) {
            if (key) {
                cityList({keyword: key}).then(res => {
                    this.thirdOptions = res.data.content;
                });
            }
        },
        addTime() {
            if (this.loginTime) {
                const a = {
                    startTime: moment(this.loginTime[0]).format('YYYY-MM-DD HH:mm:ss'),
                    endTime: moment(this.loginTime[1]).format('YYYY-MM-DD HH:mm:ss'),
                    status: 0,
                    flag: false
                };
                this.activityShows.push(a);
            }
        },
        upTime(index) {
            this.activityShows[index].flag = false;
        },
        sureTime(index) {
            this.activityShows[index].flag = true;
        },
        deleteTime(index) {
            this.activityShows.splice(index, 1);
        },
        dialogConfirm(formName) {
            this.activityResource.activityShows = [];
            if (this.activityShows.length > 0) {
                this.activityShows.forEach(item => {
                    const a = {
                        startTime: item.startTime,
                        endTime: item.endTime,
                        status: item.status,
                    }
                    this.activityResource.activityShows.push(a);
                });
            } else {
                this.$message({
                    type: 'error',
                    message: '请添加活动时间!'
                });
                return false;
            }
            if (this.activityResource.zhCnLabels.length === 0) {
                this.$message({
                    type: 'error',
                    message: '请添加活动标签!'
                });
                return false;
            }
            if (this.activityResource.zhHkLabels.length === 0) {
                this.$message({
                    type: 'error',
                    message: '请添加活动标签!'
                });
                return false;
            }
            if (this.activityResource.img.length === 0) {
                this.$message({
                    type: 'error',
                    message: '请上传活动宣传图!'
                });
                return false;
            }
            if (this.activityResource.seatsImg.length === 0) {
                this.$message({
                    type: 'error',
                    message: '请上传座位图!'
                });
                return false;
            }
            // console.log(this.activityResource);
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isEdit) {
                        activityUpdate(this.activityResource).then(res => {
                            this.$message({
                                type: 'success',
                                message: '修改成功!'
                            });
                            this.visible = false;
                            this.getList();
                        });
                    } else {
                        activityAdd(this.activityResource).then(res => {
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            });
                            this.visible = false;
                            this.getList();
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        handleResetSearch() {
          this.listQuery = Object.assign({}, defaultListQuery);
          this.getList();
        },
        handleSearchList() {
            this.listQuery.pageNum = 1;
            this.getList();
        },
        handleSelectRole(index, row) {

        },
        handleDelete(index, row) {
            this.$confirm('是否要删除该数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                activityDelete({activityId: row.activityId}).then(response => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getList();
                });
            });
        },
        handleShow(index, row) {
            activityShow({activityId: row.activityId}).then(res => {
                this.$message({
                    type: 'success',
                    message: '设置成功!'
                });
                this.getList();
            })
        },
        handleUpdate(index, row) {
            this.activityResource = row;
            this.activityShows = row.activityShows;
            this.isEdit = true;
            this.visible = true;
        },
        handleRouter(index, row) {
            this.$router.push({
                path: '/activity/notice',
                query: {
                    name: row.zhCnName,
                    id: row.activityId
                }
            })
        },
        handleSee(index, row) {
            // zhCnDescriptionUrl  zhHkDescriptionUrl
            // window.open(row.zhHkDescriptionUrl);
            this.visibleHtml = true;
            this.htmlV = row.zhCnDescriptionUrl;
        },
        showStatus(type) {
          let word = null;
          switch(type) {
            case 0:
              word = '未开始';
              break;
            case 1:
              word = '进行中';
              break;
            case 2:
              word = '已结束';
              break;
            default: break;
          }
          return word;
        },
        handleSizeChange(val) {
          this.listQuery.pageNum = 1;
          this.listQuery.pageSize = val;
          this.getList();
        },
        handleCurrentChange(val) {
          this.listQuery.pageNum = val;
          this.getList();
        },
    }
}
</script>

<style lang="scss" scoped>
.input-width {
    width: 360px;
}
.select-arr {
    display: flex;
    .div1 {
        display: flex;
        background-color: aliceblue;
        margin: 10px;
        padding: 5px 10px;
        .div2 {
            display: flex;
            flex-direction: column;
            // width: 145px;
            .div4 {
                width: 140px;
                overflow: hidden;
                // text-emphasis: ;
            }
        }
        .div3 {
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 30px;
        }
    }
}
.liang {
    background-color: #409EFF;
    color: #fff;
}
</style>
